package com.am.server.api.system.role.service.impl;

import com.am.server.api.system.role.dao.rdb.RoleDao;
import com.am.server.api.system.role.model.dto.UpdateRolePermissionDto;
import com.am.server.api.system.user.model.entity.AdminUserEntity;
import com.am.server.api.system.user.service.AdminUserService;
import com.am.server.common.util.AspectUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Service;


/**
 * @author 阮雪峰
 */
@Slf4j
@Aspect
@Service
public record UpdatePermissionAction(RoleDao roleDao, AdminUserService adminUserService) {

    @After("execution(* com.am.server.api.system.role.service.RoleService.updatePermissions(..))")
    public void doAction(final JoinPoint joinPoint) {
        final UpdateRolePermissionDto updateRolePermissionDto = AspectUtils.getParameterValueByIndex(joinPoint, 0);
        roleDao.findById(updateRolePermissionDto.getId())
                .ifPresent(role -> {
                    for (final AdminUserEntity user : role.getUsers()) {
                        adminUserService.refreshPermissionAsync(user.getId());
                    }
                });
    }
}
